package com.jack.leetcode.eachproblem_2020;

import java.util.ArrayList;
import java.util.List;

public class 全排列2 {

    public List<List<Integer>> permuteUnique(int[] nums) {
        if(nums == null){
            return new ArrayList<>();
        }
        int n = nums.length;
        quicksort(nums, 0, n - 1);
        List<List<Integer>> result = new ArrayList<>();
        boolean[] used = new boolean[n];
        dfs(used, nums, result, new ArrayList<>(), 0);
        return result;
    }

    private void dfs(boolean[] used, int[] nums, List<List<Integer>> result, List<Integer> tmp, int index){
        if(index == nums.length){
            result.add(new ArrayList<>(tmp));
            return;
        }
        for(int i = 0;i < nums.length;i++){
            if(used[i]){
                continue;
            }
            if(i > 0 && nums[i - 1] == nums[i] && !used[i-1]){
                continue;
            }
            tmp.add(nums[i]);
            used[i] = true;
            dfs(used, nums, result, tmp, index + 1);
            tmp.remove(tmp.size() - 1);
            used[i] = false;
        }
    }

    private void quicksort(int[] nums, int begin, int end){
        if(begin >= end){
            return;
        }
        int i = begin, j = end, num = nums[begin];
        while(i < j){
            while(i < j && nums[j] > num){
                j--;
            }
            if(i < j){
                nums[i++] = nums[j];
            }
            while(i < j && nums[i] < num){
                i++;
            }
            if(i < j){
                nums[j--] = nums[i];
            }
        }
        nums[i] = num;
        quicksort(nums, begin, i - 1);
        quicksort(nums, i + 1, end);
    }
}
